package com.goldcontrol.cloudweb.weixin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.goldcontrol.cloudweb.common.Constants;
import com.goldcontrol.cloudweb.controller.WechatQuartzController;
import com.goldcontrol.cloudweb.mapper.ProjectControlMapper;
import com.goldcontrol.cloudweb.mapper.ScheduledMapper;
import com.goldcontrol.cloudweb.mapper.TemplateMapper;
import com.goldcontrol.cloudweb.model.JobEntity;
import com.goldcontrol.cloudweb.model.ProjectControl;
import com.goldcontrol.cloudweb.model.TemplateEntity;
import com.goldcontrol.cloudweb.quartz.job.AccessJcmJob;
import com.goldcontrol.cloudweb.quartz.job.AccessYsJob;
import com.goldcontrol.cloudweb.quartz.job.WeatherJob;
import com.goldcontrol.cloudweb.service.ApiService;
import com.goldcontrol.cloudweb.service.TemplateService;
import com.goldcontrol.cloudweb.util.ConstantUtil;
import com.goldcontrol.cloudweb.util.HttpUtil;
import com.goldcontrol.cloudweb.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class WeixinServiceApi {


    private Logger logger = LoggerFactory.getLogger(WeixinServiceApi.class);

    @Autowired
    TemplateMapper templateMapper;

    @Autowired
    ApiService apiService;

    @Autowired
    ProjectControlMapper projectControlMapper;

    @Autowired
    ScheduledMapper scheduledMapper;

    @Value("${api_host}")
    private String api_host;

    @Value("${loginApi}")
    private String loginApi;

    @Value("${ctrlApi}")
    private String ctrlApi;

    @Value("${ctrlResultApi}")
    private String ctrlResultApi;

    @Value("${deviceItems}")
    private String deviceItems;

    @Value("${associatedLoginApi}")
    private String associatedLoginApi;

    @Value("${bindAccountApi}")
    private String bindAccountApi;

    @Value("${unbindAccountApi}")
    private String unbindAccountApi;

    @Value("${userInfoApi}")
    private String userInfoApi;

    private static final String SEND_MSG = "https://api.weixin.qq.com/cgi-bin/message/template/send";

    @Value("${tenantEname}")
    private String tenantEname;

    @Value("${tenantEname2}")
    private String tenantEname2;

    @Value("${loginname}")
    private String loginname;

    @Value("${password}")
    private String password;

    @Value("${updateDeviceItemsName}")
    private String updateDeviceItemsName;

    @Value("${currentDataDevice}")
    private String currentDataDevice;

    @Autowired
    AccessJcmJob accessJcmJob;

    @Autowired
    AccessYsJob accessYsJob;

    public String login(String username,String password,String tenant){

        if(StringUtils.isNotBlank(tenant)){
            tenantEname = tenant;
        }

        JSONObject request = new JSONObject();
        request.put("name",username);
        request.put("password",password);
        request.put("tenantEname",tenantEname);
        request.put("hash","test");
        System.out.println(request.toJSONString());
        return HttpUtil.post(loginApi,request.toJSONString());
    }

    public String login2(String username,String password){
        JSONObject request = new JSONObject();
        request.put("name",username);
        request.put("password",password);
        request.put("tenantEname",tenantEname2);
        request.put("hash","test");
        return HttpUtil.post(loginApi,request.toJSONString());
    }

    public String findUserInfo(String token,String username){
        String url = String.format(userInfoApi+"?token=%s&loginName=%s",token,username);
        return HttpUtil.get(url);
    }

    public String bindAccount(String username,String password,String openId,String tenant){
        if(StringUtils.isNotBlank(tenant)){
            tenantEname = tenant;
        }
        JSONObject request = new JSONObject();
        request.put("userName",username);
        request.put("password",password);
        request.put("tenantEname",tenantEname);
        request.put("weixin_id",openId);
        return HttpUtil.post(bindAccountApi,request.toJSONString());
    }

    public String bindAccount2(String username,String password,String openId){
        JSONObject request = new JSONObject();
        request.put("userName",username);
        request.put("password",password);
        request.put("tenantEname",tenantEname2);
        request.put("weixin_id",openId);
        return HttpUtil.post(bindAccountApi,request.toJSONString());
    }

    public String unbindAccount(String token,String openId){
        JSONObject request = new JSONObject();
        request.put("token",token);
        request.put("weixin_id",openId);
        return HttpUtil.post(unbindAccountApi,request.toJSONString());
    }

    //返回的是token
    public String loginWithOpenid(String openid){
        JSONObject param = new JSONObject();
        param.put("weixin_id",openid);
        String result = HttpUtil.post(associatedLoginApi,param.toJSONString());
        return JSONObject.parseObject(result).toJSONString();
    }

    public String sendCtrl(String token,String devid,String itemid,String value){
        String url = String.format(ctrlApi+"?token=%s&hash=test&devid=%s&itemid=%s&value=%s",token,devid,itemid,value);
        return HttpUtil.put2(url);
    }

    public String getCtrlResult(String token,String devid,String itemid,String sign){
        String url = String.format(ctrlResultApi+"?token=%s&hash=test&devid=%s&itemid=%s&sign=%s",token,devid,itemid,sign);
        return HttpUtil.get(url);
    }

    public String getProjectsList(String token){
        String url = String.format("%s/project/getProjectsList?token=%s&active=1",api_host,token);
        String result = HttpUtil.get(url);
        JSONObject projectJSONObject = JSONObject.parseObject(result);
        JSONArray projectArray = projectJSONObject.getJSONArray("data");
        HashSet<String> serialNumberSetTotal = new HashSet<String>();//所有的项目网关集合
        Map<String,Integer> typeMap = new HashMap<>();

        Map<String,List<JSONObject>> treeMap = new HashMap<>();

        for(int k=0;k<projectArray.size();k++){
            JSONObject project = projectArray.getJSONObject(k);
            String projectType = project.getString("projectType");
            String city = project.getString("city");
            if(treeMap.containsKey(city)){
                List<JSONObject> projectList = treeMap.get(city);
                projectList.add(project);
                treeMap.put(city,projectList);
            }else{
                List<JSONObject> projectList = new ArrayList<>();
                projectList.add(project);
                treeMap.put(city,projectList);
            }
            if(typeMap.get(projectType) == null){
                typeMap.put(projectType,1);
            }else{
                Integer typeCount = typeMap.get(projectType);
                typeMap.put(projectType,typeCount + 1);
            }
            //获取网关信息
            HashSet<String> serialNumberSet = dealVdevicesItems(token,project);
            serialNumberSetTotal.addAll(serialNumberSet);
        }
        projectJSONObject.put("vDeviceItemsNum",serialNumberSetTotal.size());
        int projectCount = projectArray.size();
        HashSet<String> onlineAgentSet = getAgentListInfo(token,serialNumberSetTotal);
        //处理告警 离线项目
        for(Object object : projectArray){
            if(object instanceof JSONObject) {
                JSONObject project = (JSONObject) object;
                String agentId = project.getString("serialNumber");
                if(onlineAgentSet.contains(agentId)){
                    project.put("onlineStatus",1);
                }else{
                    project.put("onlineStatus",0);
                }
            }
        }
        JSONArray typeInfo = new JSONArray();
        for(String type : typeMap.keySet()){
            Integer typeCount = typeMap.get(type);
            Map<String,Object> map = new HashMap<>();
            map.put("name",type);
            map.put("value",typeCount);
            typeInfo.add(map);
        }

        int onlineCount = onlineAgentSet.size();
        projectJSONObject.put("onlineCount",onlineCount);
        projectJSONObject.put("offlineCount",projectCount-onlineCount);
        projectJSONObject.put("typeInfo",typeInfo);
        projectJSONObject.put("tree",treeMap);

        JSONArray countArray = new JSONArray();
        for(String key : treeMap.keySet()){
            List<JSONObject> pList = treeMap.get(key);
            if(pList != null && pList.size() > 0){
                for(JSONObject item : pList){
                    JSONObject projectT = pList.get(0);
                    Double latitude = projectT.getDouble("latitude");
                    Double longitude = projectT.getDouble("longitude");
                    if(latitude != null && longitude != null){
                        JSONObject countObject  = new JSONObject();
                        countObject.put("latitude",latitude);
                        countObject.put("longitude",longitude);
                        countObject.put("count",pList.size());
                        countArray.add(countObject);
                        break;
                    }
                }
            }
        }
        projectJSONObject.put("point",countArray);
        return JSON.toJSONString(projectJSONObject,SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 网关状态信息
     */
    public HashSet<String> getAgentListInfo(String token, HashSet<String> serialNumberSetTotal){
        List<Long> agentIds = new ArrayList<Long>();
        for(String serialNumber : serialNumberSetTotal){
            agentIds.add(Long.parseLong(serialNumber));
        }
        String url = String.format("%s/agentList/condition",api_host);
        JSONObject request = new JSONObject();
        request.put("token",token);
        request.put("hash","test");
        request.put("agentIds",agentIds);
        String result =  HttpUtil.post(url,request.toJSONString());
        HashSet<String> onlineAgentSet = new HashSet<String>();
        int onlineCount = 0;
        if(StringUtils.isNotBlank(result)){
            JSONObject resultJSONObject = JSONObject.parseObject(result);
            JSONArray dataArray = resultJSONObject.getJSONArray("data");
            for(Object object : dataArray){
                if(object instanceof JSONObject){
                    JSONObject agentInfoObject = (JSONObject)object;
                    if(1 == agentInfoObject.getInteger("condition")){
                        onlineCount++;
                        onlineAgentSet.add(agentInfoObject.getString("agentid"));
                    }
                }
            }
        }
        return onlineAgentSet;
    }

    /**
     * 处理项目网关信息
     */
    public HashSet<String> dealVdevicesItems(String token,JSONObject project){
        String projectId = project.getString("id");
        //获取数据概览信息
        String result = getVdevicesItems(token,projectId);
        JSONObject resultJSONObject = JSONObject.parseObject(result);
        JSONArray dataArray = resultJSONObject.getJSONArray("data");
        HashSet<String> serialNumberSet = new HashSet<String>();
        for(Object dataObject : dataArray){
            if(dataObject instanceof JSONObject){
                JSONObject jsonObject = (JSONObject)dataObject;
                String serialNumber = jsonObject.getString("serialNumber");
                if(serialNumber.substring(0,2).contains("15")){
                    project.put("serialNumber",serialNumber);
                    serialNumberSet.add(serialNumber);
                }
            }
        }
        if(project.get("serialNumber") == null){
            project.put("serialNumber","");
        }
        return serialNumberSet;
    }

    public String getVdevicesItems(String token,String projectId){
        String url = String.format("%s/project/getVdevicesItems?token=%s&projectId=%s",api_host,token,projectId);
        return HttpUtil.get(url);
    }

    public JSONObject getHistoryLineData(Integer type,String token,String devid,String itemid) throws ParseException {
        Date eDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(type == 1 || type == null){
            String sDateStr = sdf.format(eDate);
            String eDateStr = sdf.format(eDate);
            return apiService.getItemHistory2(token,sDateStr,eDateStr,devid,itemid);
        }else if (type == 2){
            String eDateStr = sdf.format(eDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(eDate);
            calendar.add(Calendar.DATE,-6);
            String sDateStr = sdf.format(calendar.getTime());
            return apiService.getItemHistory2(token,sDateStr,eDateStr,devid,itemid);
        }else if(type == 3){
            String eDateStr = sdf.format(eDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(eDate);
            calendar.add(Calendar.DATE,-29);
            String sDateStr = sdf.format(calendar.getTime());
            return apiService.getItemHistory2(token,sDateStr,eDateStr,devid,itemid);
        }
        return new JSONObject();
    }

    public JSONArray getHistoryLineDate(Integer type) throws ParseException {
        Date eDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String eDateStr = sdf.format(eDate);
        String sDateStr = "";
        if(type == 1 || type == null){
            sDateStr = sdf.format(eDate);
        }else if (type == 2){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(eDate);
            calendar.add(Calendar.DATE,-6);
            sDateStr = sdf.format(calendar.getTime());
        }else if(type == 3){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(eDate);
            calendar.add(Calendar.DATE,-29);
            sDateStr = sdf.format(calendar.getTime());
        }
        return apiService.getHistoryDateArray(sDateStr,eDateStr);
    }

    public void createTemplate(JSONObject request){
        Integer projectId = request.getInteger("projectId");
        String templateName = request.getString("templateName");
        Integer templateId = templateService.getProjectTemplateId(projectId);
        if(templateId == null){
            templateId = templateService.getId();
            templateService.addProjectTemplate(projectId,templateId);
        }
        JSONObject dataitems = request.getJSONObject("items");
        for(String key : dataitems.keySet()){
            JSONObject item = dataitems.getJSONObject(key);
            saveTemplateItem(templateId,templateName,key,item.getString("alias"),item.getString("val"));
        }
    }

    public void deleteTemplate(Integer projectId){
        templateService.deleteProjectTemplate(projectId);
    }

    public JSONObject getProjectTemplate(Integer projectId){
        return templateService.getProjectTemplate(projectId);
    }

    public String getProjectAlarmData(String projectId,String token,String page,String perPage) throws ParseException {
        Date eDate = new Date();
        long eTime = eDate.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(eDate);
        calendar.add(Calendar.DATE,-7);
        Date sDate = calendar.getTime();
        long sTime = sDate.getTime();
        String url = String.format("%s/alarm/projectCurrentAlarmPagination?token=%s&page=%s&perPage=%s&startTime=%s",api_host,token,page,perPage,sTime);
        String res = HttpUtil.get(url);
        if(StringUtils.isNotBlank(res)){
            JSONObject jsonObject = JSON.parseObject(res);
            JSONArray newDataArray = new JSONArray();
            JSONObject result = jsonObject.getJSONObject("result");
            if(result.getJSONArray("data") != null){
                for(Object object : result.getJSONArray("data")){
                    JSONObject data = (JSONObject)object;
                    String alarmdesc = data.getString("alarmdesc");
                    int project_id = data.getInteger("project_id");
                    if(alarmdesc.indexOf("alarm status reset") < 0 && project_id == Integer.parseInt(projectId)){
                        newDataArray.add(data);
                    }
                }
            }
            Collections.reverse(newDataArray);
            result.put("data",newDataArray);
            return result.toJSONString();
        }
        return new JSONObject().toJSONString();

    }

    @Autowired
    TemplateService templateService;

    public void saveTemplateItem(Integer templateId,String templateName,String item,String alias,String val){
        TemplateEntity templateEntity = new TemplateEntity();
        templateEntity.setTemplateName(templateName);
        templateEntity.setItem(item);
        templateEntity.setAlias(alias);
        templateEntity.setVal(val);
        templateEntity.setTemplateId(templateId);
        templateService.addTemplate(templateEntity);
    }

    public void sendTemplateMsg(String openId, Object templateMsgPO){
        logger.info("send msg to [openId]:" + openId + ";[params]:" + JSON.toJSONString(templateMsgPO));
        String result = HttpUtil.post(SEND_MSG + "?access_token=" + ConstantUtil.shunxin_access_token, JSON.toJSONString(templateMsgPO));
        logger.info("result "+result);
    }

    public void sendJcmTemplateMsg(String openId, Object templateMsgPO){
        logger.info("send msg to [openId]:" + openId + ";[params]:" + JSON.toJSONString(templateMsgPO));
        logger.info("send msg to [token]:" + ConstantUtil.jcm_access_token);
        String result = HttpUtil.post(SEND_MSG + "?access_token=" + ConstantUtil.jcm_access_token, JSON.toJSONString(templateMsgPO));
        logger.info("sendJcmTemplateMsg result:"+result);
    }

    public void sendYsTemplateMsg(String openId, Object templateMsgPO){
        logger.info("send msg to [openId]:" + openId + ";[params]:" + JSON.toJSONString(templateMsgPO));
        logger.info("send msg to [token]:" + ConstantUtil.ys_access_token);
        String result = HttpUtil.post(SEND_MSG + "?access_token=" + ConstantUtil.ys_access_token, JSON.toJSONString(templateMsgPO));
        logger.info("sendYsTemplateMsg result:"+result);
    }
    
    public void setProjectControl(String token,int projectId,int control){
        ProjectControl projectControl = projectControlMapper.selectById(projectId);
        if(projectControl == null){
            ProjectControl param = new ProjectControl();
            param.setProjectId(projectId);
            param.setControl(control);
            projectControlMapper.insert(param);
        }else{
            ProjectControl param = new ProjectControl();
            param.setProjectId(projectId);
            param.setControl(control);
            projectControlMapper.update(param);
        }
    }

    /**
     * 自动控制温度
     * @param token
     * @param projectId
     */
    public void autoControlTemp(String token,int projectId){
        try{
            String result = apiService.getProjectCurrentItemData(token,String.valueOf(projectId));
            String envTemp = Constants.projectCityTempMap.get(projectId);
            if(StringUtils.isBlank(envTemp)){
                return;
            }
            JSONObject resultData = new JSONObject();
            if(StringUtils.isNotBlank(result)
                    &&  JSONObject.parseObject(result) != null
                    &&  JSONObject.parseObject(result).getJSONArray("data") != null){
                JSONArray jsonArray = JSONObject.parseObject(result).getJSONArray("data");
                for(Object object : jsonArray){
                    JSONObject jsonObject = (JSONObject)object;
                    resultData.put(jsonObject.getString("alias"),jsonObject);
                }
                JSONObject coldObject = resultData.getJSONObject("制冷设定温度");
                JSONObject hotObject = resultData.getJSONObject("制热设定温度");
                JSONObject modeObject = resultData.getJSONObject("设定模式");
                //JSONObject inObject = resultData.getJSONObject("回水温度");
                if(modeObject != null){
                    int mode = modeObject.getInteger("val");
                    if(mode == 1){
                        String tempSet = coldObject.getString("val");
                        //1制冷 2制热
                        String needSetTemp = getSetTemp(mode,Double.parseDouble(envTemp));//需要设置的温度
                        if(!tempSet.equals(needSetTemp)){
                            logger.error("自动温度控制请求,projectId:" + projectId + " mode:"+mode+" 原温度:"+tempSet+" 天气温度:"+envTemp+" 设置温度:"+needSetTemp+" 数据项:"+coldObject.toJSONString());
                            //如果回水温度不一样 重新发送请求
                            String res = sendCtrl(token,coldObject.getString("devid"),coldObject.getString("itemid"),needSetTemp);
                            if(StringUtils.isNotBlank(res)){
                                JSONObject resObject = JSONObject.parseObject(res);
                                String ctrlRes = "";
                                for(int i=0;i<5;i++){
                                    ctrlRes = getCtrlResult(token,coldObject.getString("devid"),coldObject.getString("itemid"),resObject.getString("data"));
                                }
                                logger.error("自动温度控制结果," + ctrlRes);
                            }
                        }
                    }else{
                        String tempSet = hotObject.getString("val");
                        String needSetTemp = getSetTemp(mode,Double.parseDouble(envTemp));
                        if(!tempSet.equals(needSetTemp)){
                            logger.error("自动温度控制请求,projectId:" + projectId + " mode:"+mode+" 原温度:"+tempSet+" 天气温度:"+envTemp+" 设置温度:"+needSetTemp+" 数据项:"+hotObject.toJSONString());
                            //如果回水温度不一样 重新发送请求
                            String res = sendCtrl(token,hotObject.getString("devid"),hotObject.getString("itemid"),needSetTemp);
                            if(StringUtils.isNotBlank(res)){
                                JSONObject resObject = JSONObject.parseObject(res);
                                String ctrlRes = "";
                                for(int i=0;i<5;i++){
                                    ctrlRes = getCtrlResult(token,hotObject.getString("devid"),hotObject.getString("itemid"),resObject.getString("data"));
                                }
                                logger.error("自动温度控制结果," + ctrlRes);
                            }
                        }
                    }

                }
            }
        }catch (Exception e){
            logger.error("自动控制温度设置失败 {}",e);
        }

    }

    /**
     * 根据机房温度获取需要设定的温度
     * @return
     */
    private String getSetTemp(int mode,double envTemp){
        if(1 == mode){
            if(15 <= envTemp && envTemp <= 20){
                return "25";
            }else if(21 <= envTemp && envTemp <= 25){
                return "20";
            }else if(26 <= envTemp && envTemp <= 30){
                return "18";
            }else if(envTemp >= 31){
                return "16";
            }
            return "";
        }else{
            if(5 <= envTemp && envTemp <= 15){
                return "25";
            }else if(-5 <= envTemp && envTemp <= 4){
                return "30";
            }else if(-15 <= envTemp && envTemp <= -6){
                return "40";
            }else if(envTemp <= -16){
                return "45";
            }
            return "";
        }
    }

    public List<ProjectControl> getProjectControl(List<Integer> projectIds){
        Map<String,Object> map = new HashMap<>();
        map.put("projectIds",projectIds);
        return projectControlMapper.selectByFields(map);
    }

    public Integer getProjectControl(int projectId){
        ProjectControl projectControl = projectControlMapper.selectById(projectId);
        if(projectControl == null){
            return 0;
        }
        return projectControl.getControl();
    }

    public Integer getProjectOnOff(int projectId){
         JobEntity jobEntity = scheduledMapper.selectJob(projectId,1);
         if(jobEntity != null){
             return jobEntity.getJobStatus();
         }
         return 0;
    }

    //自动刷新项目地址的天气
    public void autoRefreshWeather(){
        if(Constants.TOKEN.equals("")){
            autoRefreshToken();
        }
        String url = String.format("%s/project/getProjectsList?token=%s&active=1",api_host,Constants.TOKEN);
        String result = HttpUtil.get(url);
        JSONObject projectJSONObject = JSONObject.parseObject(result);
        JSONArray projectArray = projectJSONObject.getJSONArray("data");
        for(int k=0;k<projectArray.size();k++) {
            JSONObject project = projectArray.getJSONObject(k);
            int id = project.getInteger("id");
            String longitude = project.getString("longitude");
            String latitude = project.getString("latitude");
            String location = longitude + "," + latitude;
            JSONObject locationTempObject = apiService.getCityTemNew(longitude,latitude);
            JSONObject weaInfo = locationTempObject.getJSONObject("weaInfo");
            String temp = weaInfo.getJSONArray("HeWeather6").getJSONObject(0).getJSONObject("now").getString("tmp");
            Constants.projectCityTempMap.put(id,temp);
        }
    }

    //自动刷新项目地址的天气
    public void autoRefreshToken(){
        String res = login(loginname,password,null);
        if(res != null){
            JSONObject resObject = JSONObject.parseObject(res);
            if("100".equals(resObject.getString("status"))){
                Constants.TOKEN = resObject.getString("data");
            }
        }
    }

    public String getDeviceItems(String token,String projectId){
        String url = String.format(deviceItems+"?token=%s&projectId=%s",token,projectId);
        return HttpUtil.get(url);
    }

    public String updateDeviceName(String token,String id,String name){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        JSONObject vdevice = new JSONObject();
        vdevice.put("id",id);
        vdevice.put("name",name);
        jsonObject.put("vdevice",vdevice);

        return HttpUtil.post(updateDeviceItemsName,jsonObject.toJSONString());
    }

    public String currentDataDevice(String request){
        return HttpUtil.post(currentDataDevice,request);
    }

    public JSONObject getRoomData(String token,String vdeviceName,String projectID){
        String url = String.format("http://goldcontrol.link:8600/project/getVdeviceCurrentItemData?token=%s&projectID=%s&vdeviceName=%s",token,projectID,vdeviceName);
        String res = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(res);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        JSONObject result = new JSONObject();
        for(int i=0;i<dataArray.size();i++){
            JSONObject object = dataArray.getJSONObject(i);
            //温度设置
            if(i==0){
                result.put("tempSet",object);
            }
            //温度显示
            if(i==1){
                result.put("temp",object);
            }
            //湿度显示
            if(i==2){
                result.put("humidity",object);
            }
            //湿度显示
            if(i==3){
                result.put("power",object);
            }
            //开关机显示
            if(i==5){
                result.put("powerSet",object);
            }
        }
        return result;
    }

    public JSONObject getDeviceList(String token){
        String url = String.format("https://goldcontrol.link:8443/devicelist/status?token=%s",token);
        String res = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(res);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray list = data.getJSONArray("list");
        int active = 0;
        int leave = 0;
        int total = list.size();
        for(Object o : list){
            JSONObject object = (JSONObject)o;
            if(1 == object.getIntValue("agentcondition")){
                active = active + 1;
            }else{
                leave = leave + 1;
            }
        }
        JSONObject result = new JSONObject();
        result.put("active",active);
        result.put("leave",leave);
        result.put("total",total);
        result.put("list",list);
        return result;
    }

//    public static void main(String[] args){
//        String ss = getRoomData("84d63f04-bfcd-4ebf-bb46-230c1fd48873","经理室","2");
//        System.out.println(ss);
//    }

}
